package com.niit.zip;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.IOException;


/**
 * Date:2024/10/11
 * Author：Ys
 * Description: 解压缩文件的代码
 */
public class MRReadGZip {

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {

        Configuration conf = new Configuration();

        //构建Job对象
        Job job = Job.getInstance(conf, MRReadGZip.class.getName());
        job.setJarByClass(MRReadGZip.class);

        //input:配置输入
        Path inputPath = new Path("zip_write");
        TextInputFormat.setInputPaths(job,inputPath);

        //mapper:配置Mapper
        job.setMapperClass(MrMapper.class);
        job.setMapOutputKeyClass(NullWritable.class);
        job.setMapOutputValueClass(Text.class);

        //reducer:配置Reducer
        job.setReducerClass(MrReducer.class);
        job.setOutputKeyClass(NullWritable.class);
        job.setOutputValueClass(Text.class);

        //output:配置输出 输出的文件夹一定不能预先存在
        Path outputPath = new Path("zip_read");
        TextOutputFormat.setOutputPath(job,outputPath);

        boolean resultFlag = job.waitForCompletion(true);
        //程序退出
        System.exit(resultFlag ? 0 : 1);

    }
    //Mapper类 用于读取文件中每一条数据
    public static class MrMapper extends Mapper<LongWritable, Text, NullWritable,Text>{

        //向外（Reducer）输出的key
        private NullWritable outpuitKey = NullWritable.get();

        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, NullWritable, Text>.Context context) throws IOException, InterruptedException {
            //直接输出每条数据
            context.write(outpuitKey,value);
        }
    }
    //Reducer类 用于处理Mapper输出的数据,并对相同Key的数据进行合并  Mapper的输出等于Reducer的输入
    public static class MrReducer extends Reducer<NullWritable,Text,NullWritable,Text> {


        @Override
        protected void reduce(NullWritable key, Iterable<Text> values, Reducer<NullWritable, Text, NullWritable, Text>.Context context) throws IOException, InterruptedException {

            //直接输出每条数据
            for (Text value : values){
                context.write(key,value);
            }

        }
    }

}
